import React, {Component, Fragment } from 'react';
import {
  Form,
  Input,
  Modal,
  Button,
  Table,
  Row, Col, Divider, Select
} from 'antd/lib/index';
import TextArea from 'antd/es/input/TextArea';
import { connect } from 'dva/index';
const { Option } = Select;
const FormItem = Form.Item;


const entityNameSpace = 'micro';
@connect(({ micro, loading }) => ({
  micro,
  loading: loading.models.micro,
}))
class MicroForm extends Component {
  completeCallBack;
  projectId;

  state = {
    visible: false,
    radioDisable: false,
    projectInfo: {},
    databaseList: [],
  };

  columns = [
    {
      title: '服务',
      dataIndex: '-',
      render:(_,record)=>(
        <div>
          <span>groupId:{record.groupId}</span>
          <br />
          <span>artifactId:{record.artifactId}</span>
          <br />
          <span>version:{record.version}</span>
        </div>
      )
    },
    {
      title: '服务介绍',
      dataIndex: '-',
      render:(_,record)=>(
        <div>
          <span>name:{record.name}</span>
          <br />
          <span>description:{record.description}</span>
        </div>
      )
    },
    {
      title: '访问路径',
      dataIndex: 'contextPath',
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <a
            onClick={this.handleEntityFormModalVisible.bind(this, true, record.id)}
          >
            修改
          </a>
          <Divider type="vertical"/>
          <a onClick={this.handleRemoveEntity.bind(this, record)}>删除</a>
        </Fragment>
      ),
    },
  ];


  componentDidMount() {
    this.props.onRef(this);
  }


  handleReloadTableList = () => {
    const { dispatch,projectId } = this.props;

    dispatch({
      type: `${entityNameSpace}/queryEntityPageList`,
      payload: { projectId : projectId },
    });

  };

  handleEntityFormModalVisible = (flag, entityId) => {

    const { dispatch,projectInfo } = this.props;

    let obj = {};
    if (projectInfo) {
      obj.apiProject = '1';
      obj.groupId = projectInfo.groupId;
      obj.artifactId = `${projectInfo.artifactId}-`;
      obj.contextPath = '/';
      obj.version = '1.0';
    }

    if (flag && entityId) {
      dispatch({
        type: `${entityNameSpace}/detailEntity`,
        payload: { id: entityId },
      });
    } else {
      dispatch({
        type: `${entityNameSpace}/changeDetailEntity`,
        payload: obj,
      });
    }
  };

  handleRemoveEntity = record => {
    const { dispatch } = this.props;

    Modal.confirm({
      title: '确认',
      content: '是否确认删除',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: `${entityNameSpace}/removeEntity`,
          payload: record,
          callback: () => {
            this.handleReloadTableList();
          },
        });
      },
    });
  };


  handleModalVisible = (visible, callBack, id) => {
    this.completeCallBack = callBack;
    const { form } = this.props;
    this.setState({
      ...this.state,
      visible: visible,
      radioDisable: id ? true : false,
      projectInfo: {},
    });
    if (visible) {
      // form reset
      form.resetFields();
      this.projectId = id;
      this.handleReloadTableList();
      this.handleEntityFormModalVisible(false);
    }
  };


  handleSearch = () => {
    const { form } =this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      this.handleEntityUpdate(fieldsValue);
    });
  };

  handleEntityUpdate = fieldsValue => {
    const { dispatch, [entityNameSpace]: { entityInfoObj } ,projectId } = this.props;

    let formData = {...fieldsValue,projectId:projectId};
    if (entityInfoObj.id) {
      formData = {
        ...fieldsValue,
        id: entityInfoObj.id
      };
    }

    dispatch({
      type: `${entityNameSpace}/updateEntity`,
      payload: formData,
      callback: () => {
        this.handleEntityFormModalVisible(false);
        this.handleReloadTableList();
      },
    });
  };


  handleCancel = () => {
    this.setState({
      ...this.state,
      visible: false
    });
  };


  renderSimpleForm() {
    const {
      form, [entityNameSpace]: { entityInfoObj }
    } = this.props;
    return (
      <Form >
        <Row gutter={16}>
          <Col span={6}>
            <FormItem>
              {form.getFieldDecorator('name', {
                initialValue: entityInfoObj.name,
                rules: [{
                  required: true,
                  message: '请输入服务名！'
                }],
              })(<Input placeholder="服务名"/>)}
            </FormItem>
          </Col>
          <Col span={6}>
            <FormItem>
              {form.getFieldDecorator('groupId', {
                initialValue: entityInfoObj.groupId,
                rules: [{
                  required: true,
                  message: '请输入groupId！'
                }],
              })(<Input placeholder="例：com.test"/>)}
            </FormItem>
          </Col>
          <Col span={6}>
            <FormItem>
              {form.getFieldDecorator('artifactId', {
                initialValue: entityInfoObj.artifactId,
                rules: [{
                  required: true,
                  message: '请输入artifactId！'
                }],
              })(<Input placeholder="例：-order"/>)}
            </FormItem>
          </Col>
          <Col span={6}>
            <FormItem>
              {form.getFieldDecorator('contextPath', {
                initialValue: entityInfoObj.contextPath,
                rules: [{
                  required: true,
                  message: '请输入访问路径！'
                }],
              })(<Input placeholder="访问路径"/>)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={6}>
            <FormItem>
              {form.getFieldDecorator('version', {
                initialValue: entityInfoObj.version,
                rules: [{
                  required: true,
                  message: '请输入版本号！'
                }],
              })(<Input placeholder="版本"/>)}
            </FormItem>
          </Col>
          <Col span={6}>
            <FormItem>
              {form.getFieldDecorator('apiProject', {
                initialValue: entityInfoObj.apiProject,
                rules: [{
                  required: true,
                  message: '请选择！'
                }],
              })(<Select placeholder='请选择' style={{ width: '100%' }}>
                  <Option value='1'>Api</Option>
                  <Option value='0'>微服务</Option>
              </Select>)}
            </FormItem>
          </Col>
          <Col span={6}>
            <FormItem>
              {form.getFieldDecorator('description', {
                initialValue: entityInfoObj.description,
                rules: [{
                  required: true,
                  message: '请输入简介！'
                }],
              })(<TextArea placeholder="简介"/>)}
            </FormItem>
          </Col>
          <Col span={6}>
            <Button type="primary" onClick={()=> this.handleSearch()}>
              添加
            </Button>
          </Col>
        </Row>
      </Form>
    );
  }

  render() {

    const { visible } = this.state;
    const { [entityNameSpace]: { entityPageResult },
    } = this.props;
    let data =[];
    if (entityPageResult.list){
      data = entityPageResult.list;
    }

    return (
      <Modal
        width={1000}
        visible={visible}
        keyboard={false}
        maskClosable={false}
        title="模块管理"
        onCancel={this.handleCancel}
        footer={[
          <Button key="back" onClick={this.handleCancel}>
            关闭
          </Button>
        ]}
      >
        {this.renderSimpleForm()}
        <Table
          rowKey="id"
          bordered={false}
          onRow={false}
          pagination={false}
          cellspaceing={50}
          dataSource={data}
          columns={this.columns}
        />

      </Modal>
    );
  }
}

export default Form.create()(MicroForm);
